package com.desiy.controller;

import com.desiy.entity.Admin;
import com.desiy.service.AdminService;
import com.desiy.utils.MsgData;
import com.desiy.utils.ResponseDTO;
import com.desiy.vo.AdminVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;

/**
 * @author Desiy
 * @date 2020/9/20 9:53
 */


@RestController
@CrossOrigin
public class AdminController {

    // LoggerFactory 取代System.out.println()
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    AdminService adminService;


    @RequestMapping("listAdmin")
    public Collection<Admin> listAdmin() {
        Collection<Admin> admins = adminService.adminList();
        return admins;
    }

    @RequestMapping("/listAdminByUsername")
    public Collection<Admin> listAdminByUsername(@RequestBody String userInfo) {
        String[] strArr = StringUtils.split(userInfo, "=");
        for (int i = 0; i < strArr.length; i++) {
            logger.info("前端登录成功留下的username：" + strArr[0]);
        }
        List<Admin> admins = adminService.adminListByUsername(strArr[0]);
//        logger.info("admin: {}"+admins);
        return admins;
    }

    @RequestMapping("/add/admin")
    public MsgData addEmp(@RequestBody Admin admin) {
        MsgData msgData = new MsgData<>();
        logger.info("前端获取的user：" + admin);
        if (admin == null) {
            msgData.setCode(201);
            return msgData;
        } else {
            adminService.add(admin);
            msgData.setCode(200);
            return msgData;
        }
    }

    @RequestMapping("admin/del/{id}")
    public MsgData del(@PathVariable Integer id){
        MsgData msgData = new MsgData<>();
        if (id != null){
            adminService.del(id);
            msgData.setCode(200);
        }else {
            msgData.setCode(201);
        }
        return msgData;
    }

    @RequestMapping("/admin/edit/{id}")
    @CrossOrigin
    public ResponseDTO edit(@PathVariable Integer id){
        ResponseDTO responseDTO = new ResponseDTO();
        logger.info("前端发送的id:"+id);
        AdminVO adminVO = adminService.edit(id);
        return responseDTO.success(adminVO);
    }
}
